package com.onvifdemo.listener;

import be.teletask.onvif.listeners.OnvifResponseListener;
import be.teletask.onvif.models.OnvifDevice;
import be.teletask.onvif.responses.OnvifResponse;
import com.alibaba.fastjson.JSONObject;
import com.onvifdemo.Entity.Common;
import com.onvifdemo.dto.DeviceInfo;
import com.onvifdemo.util.IsXmlUtil;
import com.onvifdemo.util.TimeUtil;
import com.onvifdemo.util.XmlToJsonUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CountDownLatch;

public class MyDeviceTimeListener implements OnvifResponseListener {

    public void onResponse(OnvifDevice onvifDevice, OnvifResponse response) {
        System.out.println("返回的response" + response);
        if (null != response) {
            getTime(onvifDevice, response.getXml());
        }
        if (Common.cdlTime != null) {
            Common.cdlTime.countDown();
        }

    }

    public void onError(OnvifDevice onvifDevice, int errorCode, String errorMessage) {
        String hostName = onvifDevice.getHostName().substring(onvifDevice.getHostName().lastIndexOf("/") + 1);
        String deviceIP = hostName;
        if (Common.deviceTimeMap.containsKey(deviceIP)) {
            DeviceInfo haveDevice = Common.deviceTimeMap.get(deviceIP);
            haveDevice.setErrorCode(errorCode);
            if (IsXmlUtil.isXmlDocument(errorMessage)) {
                JSONObject jsobj = XmlToJsonUtils.xmlToJson(errorMessage);
                if (null != jsobj) {
                    if (null != jsobj.getJSONObject("Fault")) {
                        String errorText = jsobj.getJSONObject("Fault").getJSONObject("Detail").getString("Text");
                        haveDevice.setErrorMsg(errorText);
                    }
                }
            } else {
                haveDevice.setErrorMsg(errorMessage);
            }
        } else {
            DeviceInfo device = new DeviceInfo();
            device.setDeviceIP(deviceIP);
            device.setErrorCode(errorCode);
            if (IsXmlUtil.isXmlDocument(errorMessage)) {
                JSONObject jsobj = XmlToJsonUtils.xmlToJson(errorMessage);
                if (null != jsobj) {
                    if (null != jsobj.getJSONObject("Fault")) {
                        String errorText = jsobj.getJSONObject("Fault").getJSONObject("Reason").getString("Text");
                        device.setErrorMsg(errorText);
                    }
                }
            } else {
                device.setErrorMsg(errorMessage);
            }

            Common.deviceTimeMap.put(deviceIP, device);
        }

        Common.cdlTime.countDown();
    }

    /**
     * 获取时间或ntp
     *
     * @param xml
     * @return
     */
    private void getTime(OnvifDevice onvifDevice, String xml) {
        // System.out.println(xml);

        String hostName = onvifDevice.getHostName().substring(onvifDevice.getHostName().lastIndexOf("/") + 1);
        String deviceIP = hostName;

        DeviceInfo myDevice = new DeviceInfo();
        myDevice.setDeviceIP(deviceIP);

        if (xml.contains("<tds:GetSystemDateAndTimeResponse>")) {

            if (IsXmlUtil.isXmlDocument(xml)) {

                JSONObject timeObjet = XmlToJsonUtils.xmlToJson(xml);
                JSONObject response = timeObjet.getJSONObject("GetSystemDateAndTimeResponse");
                JSONObject sysTime = response.getJSONObject("SystemDateAndTime");
                JSONObject time = sysTime.getJSONObject("LocalDateTime").getJSONObject("Time");

                String second = time.getString("Second");
                String hmc = time.getString("Hour") + ":" + time.getString("Minute") + ":" + second;

                JSONObject date = sysTime.getJSONObject("LocalDateTime").getJSONObject("Date");
                String mouth = date.getString("Month");

                String day = date.getString("Day");

                String ymd = date.getString("Year") + "-" + mouth + "-" + day;

                String timetemp = ymd + " " + hmc;
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                try {
                    Date d = sdf.parse(timetemp);
                    String tim = sdf.format(d);
                    myDevice.setTime(tim);

                    Long systime = System.currentTimeMillis();
                    Date sysDate = new Date(systime);
                    myDevice.setSysTime(sdf.format(sysDate));

                    /**
                     * if (TimeUtil.timeTongBu(tim, systime)) { myDevice.setIs_lock_syn("同步"); } else {
                     * myDevice.setIs_lock_syn("不同步"); }
                     */

                    myDevice.setTime_diff(TimeUtil.timeDiff(tim, systime));
                } catch (ParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            } else {

            }

            addDevcieToMap(myDevice);
        }

    }

    /**
     *
     * @param device
     */
    private void addDevcieToMap(DeviceInfo device) {

        // 如果包含则更新设备信息。
        if (Common.deviceTimeMap.containsKey(device.getDeviceIP())) {

            DeviceInfo haveDevice = Common.deviceTimeMap.get(device.getDeviceIP());

            haveDevice.setTime(device.getTime());

        } else {
            Common.deviceTimeMap.put(device.getDeviceIP(), device);
        }
    }

}
